<template>
  <mt-popup
    v-model="popupVisible"
    position="right"
    :modal="false"
    class="store-choice"
  >
    <div class="page">
      <div class="scroll-view">
        <customHeader
          v-if="!multipleChoice && hasTotal"
          middleTitle="选择门店"
          @leftCallBack="popupHide"
          :jsBridgeBack="false"
        />
        <customHeader
          v-if="!multipleChoice && !hasTotal"
          middleTitle="选择门店"
          @leftCallBack="back"
          :jsBridgeBack="false"
        />
        <customHeader
          v-if="multipleChoice"
          middleTitle="选择门店"
          @leftCallBack="back"
          :jsBridgeBack="false"
        />
        <div class="tip-msg" v-if="tipMsg && notPassMini">
          <i class="zhk-order_fa"></i>
          <span>{{ tipMsg }}</span>
        </div>
        <div class="tip-msg" v-if="msg">
          <i class="zhk-order_fa"></i>
          <span>{{ msg }}</span>
        </div>
        <searchBar @search="searchCallbck" :clearVal="clearVal" />
        <div class="scroll-ct page-body">
          <div class="store-choice-list">
            <!-- <div v-if="multipleChoice" class="item all" @click="choiceAll" selectName="全部门店">
              <div class="item-ct">
                <span :class="selectAllFlag?'list_select label':'list-wx label'">全部门店</span>
              </div>
            </div> -->
            <div
              v-if="hasTotal && !multipleChoice"
              class="item all"
              @click="singleChoiceAll"
              selectName="全部门店"
            >
              <div class="item-ct">
                <span
                  :class="
                    singleChoiceAllFlag ? 'list_select label' : 'list-wx label'
                  "
                  >全部门店</span
                >
              </div>
            </div>
          </div>
          <div
            class="store-choice-list"
            v-for="(item, index) in listData"
            :key="index"
            v-show="item.visible"
          >
            <div class="head">{{ item.head }}</div>
            <div
              class="item"
              @click="storeItemChoice(childitem.key, childitem.data.disabled)"
              v-for="(childitem, index) in item.children"
              :key="index"
            >
              <div
                :class="
                  childitem.data.disabled ? 'item-ct disabled' : 'item-ct'
                "
                v-show="childitem.visible"
              >
                <span
                  :class="
                    childitem.select ? 'list_select label' : 'list-wx label'
                  "
                >
                  <template v-if="multipleChoice">
                    <i v-if="!childitem.select" class="zhk-list-wx"></i>
                    <i v-if="childitem.select" class="zhk-list_select"></i>
                  </template>
                  <span>{{ childitem.label }}</span>
                  <span v-if="childitem.data.tag" class="tag">{{
                    childitem.data.tag
                  }}</span>
                </span>
              </div>
            </div>
          </div>
          <noData msg="暂无数据" v-if="listData.length === 0" />
        </div>
        <div class="multiple-ope" v-if="multipleChoice">
          <div class="check-all" @click="choiceAll">
            <i class="zhk-list-wx" v-show="!selectAllFlag"></i>
            <i class="zhk-list_select" v-show="selectAllFlag"></i>
            <span>全选</span>
          </div>
          <div
            class="select-amount"
            :class="{ disabled: selectCount === 0 && noneCheck }"
            @click="popupHide"
          >
            确定&nbsp;({{ selectCount }})
          </div>
        </div>
      </div>
    </div>
  </mt-popup>
</template>

<script>
import Vue from "vue";
import { Popup, Toast } from "mint-ui";
import customHeader from "../../components/header/header";
import noData from "../../components/noData/noData";
import searchBar from "../../components/searchBar/searchBar";
Vue.component(Popup.name, Popup);
export default {
  name: "StoreChoice",
  data() {
    return {
      selectCount: 0, //门店选中数
      listData: [], //门店列表数据
      popupVisible: false,
      storeName: "选择门店",
      selectAllFlag: false,
      singleChoiceAllFlag: false,
      dataSource: [], //接口返回的data
      currentSelect: this.current, //用于点返回记录还原数据
      notPassMini: false, //不符合小程序条件的门店
      clearVal: null //清空搜索框的值
    };
  },
  props: {
    multipleChoice: {
      //是否为多选
      type: Boolean,
      default: false
    },
    multipleSelectAll: {
      //多选下，默认是否为全选
      type: Boolean,
      default: true
    },
    hasTotal: {
      //是否显示全部门店
      type: Boolean,
      default: true
    },
    current: {
      //当前选中的门店
      type: Array,
      default: []
    },
    isReset: {
      //重置
      default: false
    },
    tipMsg: {
      //提示消息
      default: ""
    },
    msg: {
      //提示消息
      default: ""
    },

    //是否过滤掉其他状态门店，只显示审核通过的门店
    statusFilter: {
      type: Boolean,
      default: false
    },
    //门店列表的请求接口地址（默认请求：/newapp/shop/getShopSelect.do）
    reqUrl: {
      type: String
    },

    //一个都不选的时候点确定是否校验
    noneCheck: {
      type: Boolean,
      default: true
    },
    //全选返回空
    returnAllNull: {
      type: Boolean,
      default: true
    },
    //父组件传过来的数据源
    sourceData: Object,
    //返回的是否是shopId的集合 true shopId的集合 flase 返回字符串all
    allShopIdsFlag:{
      type: Boolean,
      default: true
    }
  },
  mounted() {},
  methods: {
    searchCallbck(v) {
      if (v) {
        //有值搜索
        for (let city of this.listData) {
          let hasVisible = false;
          for (let store of city.children) {
            if (store.label.indexOf(v) !== -1) {
              store.visible = true;
              hasVisible = true;
            } else {
              store.visible = false;
            }
          }
          city.visible = hasVisible;
        }
      } else {
        //无值还原
        for (let city of this.listData) {
          city.visible = true;
          for (let store of city.children) {
            store.visible = true;
          }
        }
      }
      this.getSelectCount(this.listData);
    },
    closeOnly() {
      this.popupVisible = false;
    },
    //重置为全选
    reset() {
      if (this.multipleChoice) {
        this.selectAllFlag = this.multipleSelectAll;
        for (let city of this.listData) {
          city.visible = true;
          for (let store of city.children) {
            store.visible = true;
            store.select = this.multipleSelectAll;
          }
        }
      }
      if (!this.multipleChoice) {
        this.singleChoiceAllFlag = true;
        for (let city of this.listData) {
          city.visible = true;
          for (let store of city.children) {
            store.visible = true;
            store.select = false;
          }
        }
      }
    },
    popupShow() {
      this.popupVisible = true;
    },
    //返回
    popupHide() {
      this.clearVal = new Date();
      let selectArr = [];
      if (this.selectAllFlag || this.singleChoiceAllFlag) {
        this.storeName = "全部门店";
      } else {
        this.storeName = "选择门店";
      }

      const listData = this.listData;  
      let storeList = [];
      if (this.singleChoiceAllFlag) {
        selectArr.push({ selectName: "全部门店", selectKey: "all" });
      } else {
        let selectAllFlag = true;
        // let storeList = [];
        for (let city of listData) {
          for (let store of city.children) {
            storeList.push({ selectName: store.label, selectKey: store.key });
            if (store.select === true && store.visible) {
              selectArr.push({ selectName: store.label, selectKey: store.key });
              if (!this.multipleChoice) {
                this.storeName = store.label;
              }
            } else {
              selectAllFlag = false;
            }
          }
        }
        if (!this.allShopIdsFlag&&selectAllFlag) {
          if(storeList.length == 1){
            selectArr = storeList
          }else{
            selectArr = [{ selectName: "全部门店", selectKey: "all" }]
          }
        }
      }

      if (
        this.multipleChoice &&
        selectArr.length == 0 &&
        this.popupVisible == true &&
        this.noneCheck
      ) {
        Toast("请选择门店");
        return;
      }
      this.$emit(
        "listenToStoreSelect",
        selectArr,
        storeList.length==selectArr.length ? this.storeName : (!this.multipleChoice&&this.storeName),
        this.returnAllNull && this.selectAllFlag
      );
      this.currentSelect = selectArr;
      this.popupVisible = false;
    },
    //返回（不传值）
    back() {
      this.clearVal = new Date();
      this.listData = this.checkDataSource(this.dataSource, this.currentSelect);
      this.popupVisible = false;
    },
    //选择全部
    choiceAll() {
      const selectAllFlag = this.selectAllFlag;
      this.selectAllFlag = !selectAllFlag;
      for (let i = 0; i < this.listData.length; i++) {
        for (let j = 0; j < this.listData[i].children.length; j++) {
          if (!this.listData[i].children[j].data.disabled) {
            this.listData[i].children[j].select = !selectAllFlag;
          }
        }
      }
      this.getSelectCount(this.listData);
    },
    //单选选择全部
    singleChoiceAll() {
      this.singleChoiceAllFlag = true;

      for (let i = 0; i < this.listData.length; i++) {
        for (let j = 0; j < this.listData[i].children.length; j++) {
          this.listData[i].children[j].select = false;
        }
      }
      this.popupHide();
    },
    //门店选择
    storeItemChoice(key, disabled) {
      if (disabled) {
        return false;
      }
      const listData = this.listData;
      if (this.multipleChoice) {
        //多选
        for (let i = 0; i < this.listData.length; i++) {
          for (let j = 0; j < this.listData[i].children.length; j++) {
            if (this.listData[i].children[j].key == key) {
              let flag = this.listData[i].children[j].select;
              this.listData[i].children[j].select = !flag;
            }
          }
        }
        this.getSelectCount(this.listData);
        //如果每一项都选中全部门店勾选
        for (let i = 0; i < this.listData.length; i++) {
          for (let j = 0; j < this.listData[i].children.length; j++) {
            if (this.listData[i].children[j].select == false) {
              this.selectAllFlag = false;
              return;
            } else {
              this.selectAllFlag = true;
            }
          }
        }
      } else {
        this.singleChoiceAllFlag = false;
        //单选
        for (let i = 0; i < this.listData.length; i++) {
          for (let j = 0; j < this.listData[i].children.length; j++) {
            if (this.listData[i].children[j].key == key) {
              let flag = this.listData[i].children[j].select;
              this.listData[i].children[j].select = true;
            } else {
              this.listData[i].children[j].select = false;
            }
          }
        }
        this.popupHide();
      }
    },
    checkDataSource(data, currentSelect) {
      let shopList = [];
      let checkCount = 0;
      let storeCount = 0;
      if (data != null && JSON.stringify(data) != "{}") {
        for (var cityName in data) {
          var childrenList = [];
          if (data[cityName] != null && data[cityName].length > 0) {
            for (var i = 0; i < data[cityName].length; i++) {
              //回显选中
              const isChecked =
                currentSelect.filter(item => {
                  return item.selectKey === data[cityName][i].shopId;
                }).length > 0;

              if (data[cityName][i]["passMini"] === false) {
                this.notPassMini = true;
              }
              if (!isChecked && data[cityName][i]["disabled"]) {
                data[cityName][i].disabled = true;
              } else {
                data[cityName][i].disabled = false;
              }

              if (data[cityName][i]["passMini"]) {
                if (isChecked) {
                  checkCount = checkCount + 1;
                }
                childrenList.push({
                  visible: true,
                  key: data[cityName][i].shopId,
                  label: data[cityName][i].shopName,
                  select: isChecked,
                  data: data[cityName][i]
                });
              } else if (data[cityName][i]["passMini"] === undefined) {
                if (
                  !this.statusFilter ||
                  (this.statusFilter &&
                    data[cityName][i].auditStatus !== 1 &&
                      data[cityName][i].auditStatus !== 3)
                ) {
                  //状态筛选 审批中：1  审批驳回：3  的门店不显示
                  if (isChecked) {
                    checkCount = checkCount + 1;
                  }
                  childrenList.push({
                    visible: true,
                    key: data[cityName][i].shopId,
                    label: data[cityName][i].shopName,
                    select: isChecked,
                    data: data[cityName][i]
                  });
                }
              }
            }
          }
          childrenList.length > 0 &&
            shopList.push({
              head: cityName,
              children: childrenList,
              visible: true
            });
          storeCount = storeCount + childrenList.length;
        }
      }
      this.selectAllFlag =
        storeCount != 0 && checkCount === storeCount ? true : false;
      this.selectCount = checkCount;
      return shopList;
    },
    getData(callBack) {
      if (this.sourceData) {
        this.listData = this.checkDataSource(
          this.sourceData,
          this.currentSelect
        );
        callBack && callBack();
        return;
      }
      const url = this.reqUrl ? this.reqUrl : "/newapp/shop/getShopSelect.do";
      this.ajax({
        url: url,
        type: "get",
        data: {},
        controlLoading: false
      })
        .then(res => {
          if (res.success) {
            const data = res.resultObject;
            this.dataSource = data;
            this.listData = this.checkDataSource(data, this.currentSelect);
            callBack && callBack();
          }
        })
        .catch(function(err) {

        });
    },
    //当前选中的门店数
    getSelectCount(listData) {
      let selectCount = 0;
      for (let i = 0; i < listData.length; i++) {
        for (let j = 0; j < listData[i].children.length; j++) {
          if (listData[i].children[j].select && listData[i].children[j].visible) {
            selectCount = selectCount + 1;
          }
        }
      }
      this.selectCount = selectCount;
    }
  },
  components: {
    customHeader,
    searchBar,
    noData
  },
  watch: {
    popupVisible(newVal, oldVal) {
      if (newVal && this.listData.length === 0) {
        this.getData(() => {
          if (this.current.length > 0 && this.current[0].selectKey != "") {
            return;
          }
          this.reset();
          let selectArr = [];
          for (let city of this.listData) {
            for (let store of city.children) {
              if (store.select === true) {
                selectArr.push({
                  selectName: store.label,
                  selectKey: store.key
                });
              }
            }
          }
          this.currentSelect = selectArr;
        });
      }
    },
    isReset(newVal, oldVal) {
      if (newVal) {
        this.reset();
        this.popupHide();
      }
    },
    current(newVal, oldVal) {
      if (JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
        if (newVal.length > 0 && newVal[0].selectKey) {
          this.currentSelect = newVal;
          const source = this.sourceData ? this.sourceData : this.dataSource;
          this.listData = this.checkDataSource(source, newVal);
        }
      }
    },
    currentSelect(newVal, oldVal) {
      if (this.multipleChoice) {
        this.selectCount = newVal.length;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
@import "StoreChoice";
</style>
